<template>
  <div class="app-container">
    <!-- 合同模板 -->
    <el-card class="h full" shadow="never" v-loading="loading">
      <template #header>
        合同模板
        <div style="margin-bottom: 10px">
          <el-link type="warning">提示：公司章和客户签字为固定字段，用于生成电子签</el-link>
        </div>
      </template>
      <div class="h">
        <el-form ref="basicFormRef" :model="formData" :rules="rules" label-width="120px" label-position="left"
          class="h">
          <el-form-item label="合同名称" prop="name">
            <el-input v-model="formData.name" style="width: 400px" placeholder="请输入合同名称" />
          </el-form-item>
          <el-form-item label="合同内容" prop="content" style="height: 80%">
            <WangEditor class="w h" type="contract" v-model="formData.content" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSubmit">保存模板</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import ContractTempAPI, {
  ContractTempForm,
  defaultContractTempForm,
} from "@/api/flow/contractTemp.api";
import WangEditor from "@/components/WangEditor/index.vue";
import { cloneDeep } from "lodash-es";
import { useTagsViewStore } from "@/store";

defineOptions({
  name: "ContractTempEdit",
  inheritAttrs: false,
});

const route = useRoute();
const tagsViewStore = useTagsViewStore();

const tempId = ref(""); //合同模板id
const loading = ref(false);
const formData = reactive<ContractTempForm>(cloneDeep(defaultContractTempForm));
const rules = reactive({
  name: [{ required: true, message: "合同模板名称不能为空", trigger: "blur" }],
  content: [{ required: true, message: "合同内容不能为空", trigger: "blur" }],
});

const basicFormRef = ref();

onActivated(() => {
  if (route.query.id == tempId.value) return;
  tempId.value = route.query.id as string;
  loadContractDetail(tempId.value);
});

const loadContractDetail = async (id?: string) => {
  if (!id || id === "0") {
    Object.assign(formData, cloneDeep(defaultContractTempForm));
    return;
  }
  await ContractTempAPI.getFormData(id).then((data) => {
    Object.assign(formData, data);
  });
};

/**
 * 提交表单
 */
const handleSubmit = () => {
  basicFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      if (!formData.content) {
        ElMessage.error("请编写合同内容");
        return;
      }
      loading.value = true;
      // 处理数据
      try {
        formData.content = formData.content.replaceAll(/\<br\>/g, "<br/>");
        formData.id
          ? await ContractTempAPI.update(formData)
          : await ContractTempAPI.create(formData);
        ElMessage.success("保存模板成功");
        tagsViewStore.closeCurrentView();
      } catch (error) {
        console.error("保存模板失败");
      }
      loading.value = false;
    }
  });
};
</script>
